<%
local v2ray_version=luci.sys.exec("/usr/bin/xray -version | awk '{print $2}' | sed -n 1P")
-%>

<script type="text/javascript">
	//<![CDATA[
	var v2rayInfo;
	var tokenStr = '<%=token%>';
	var noUpdateText = '<%:It is the latest version%>';
	var updateSuccessText = '<%:Update successful%>';
	var clickToUpdateText = '<%:Click to update%>';
	var inProgressText = '<%:Updating...%>';
	var unexpectedErrorText = '<%:Unexpected error%>';
	var updateInProgressNotice = '<%:Updating, are you sure to close?%>';
	var downloadingText = '<%:Downloading...%>';
	var decompressioningText = '<%:Unpacking...%>';
	var movingText = '<%:Moving...%>';

	window.onload = function() {
		var v2rayCheckBtn = document.getElementById('_v2ray-check_btn');
		var v2rayDetailElm = document.getElementById('_v2ray-check_btn-detail');
	};

	function addPageNotice_v2ray() {
		window.onbeforeunload = function(e) {
			e.returnValue = updateInProgressNotice;
			return updateInProgressNotice;
		};
	}

	function removePageNotice_v2ray() {
		window.onbeforeunload = undefined;
	}

	function onUpdateSuccess_v2ray(btn) {
		alert(updateSuccessText);

		if(btn) {
			btn.value = updateSuccessText;
			btn.placeholder = updateSuccessText;
			btn.disabled = true;
		}

		window.setTimeout(function() {
			window.location.reload();
		}, 1000);
	}

	function onRequestError_v2ray(btn, errorMessage) {
		btn.disabled = false;
		btn.value = btn.placeholder;

		if(errorMessage) {
			alert(errorMessage);
		}
	}

	function doAjaxGet(url, data, onResult) {
		new XHR().get(url, data, function(_, json) {
			var resultJson = json || {
				'code': 1,
				'error': unexpectedErrorText
			};

			if(typeof onResult === 'function') {
				onResult(resultJson);
			}
		})
	}

	function onBtnClick_v2ray(btn) {
		if(v2rayInfo === undefined) {
			checkUpdate_v2ray(btn);
		} else {
			doUpdate_v2ray(btn);
		}
	}

	function checkUpdate_v2ray(btn) {
		btn.disabled = true;
		btn.value = inProgressText;

		addPageNotice_v2ray();

		var ckeckDetailElm = document.getElementById(btn.id + '-detail');

		doAjaxGet('<%=url([[admin]], [[services]], [[v2ray_server]], [[check]])%>', {
			token: tokenStr,
			arch: ''
		}, function(json) {
			removePageNotice_v2ray();

			if(json.code) {
				v2rayInfo = undefined;
				onRequestError_v2ray(btn, json.error);
			} else {
				if(json.update) {
					v2rayInfo = json;
					btn.disabled = false;
					btn.value = clickToUpdateText;
					btn.placeholder = clickToUpdateText;
					
					if(ckeckDetailElm) {
						var urlNode = '';
						if(json.version) {
							urlNode = '<em style="color:red;">最新版本号：' + json.version + '</em>';
							if(json.url && json.url.html) {
								urlNode = '<a href="' + json.url.html + '" target="_blank">' + urlNode + '</a>';
							}
						}
					ckeckDetailElm.innerHTML = urlNode;
					}
				} else {
					btn.disabled = true;
					btn.value = noUpdateText;
				}
			}
		});
	}

	function doUpdate_v2ray(btn) {
		btn.disabled = true;
		btn.value = downloadingText;

		addPageNotice_v2ray();

		var v2rayUpdateUrl = '<%=url([[admin]], [[services]], [[v2ray_server]], [[update]])%>';
		// Download file
		doAjaxGet(v2rayUpdateUrl, {
			token: tokenStr,
			url: v2rayInfo ? v2rayInfo.url.download : ''
		}, function(json) {
			if(json.code) {
				removePageNotice_v2ray();
				onRequestError_v2ray(btn, json.error);
			} else {
				btn.value = decompressioningText;

				// Extract file
				doAjaxGet(v2rayUpdateUrl, {
					token: tokenStr,
					task: 'extract',
					file: json.file,
					subfix: v2rayInfo ? v2rayInfo.type : ''
				}, function(json) {
					if(json.code) {
						removePageNotice_v2ray();
						onRequestError_v2ray(btn, json.error);
					} else {
						btn.value = movingText;

						// Move file to target dir
						doAjaxGet(v2rayUpdateUrl, {
							token: tokenStr,
							task: 'move',
							file: json.file
						}, function(json) {
							removePageNotice_v2ray();
							if(json.code) {
								onRequestError_v2ray(btn, json.error);
							} else {
								onUpdateSuccess_v2ray(btn);
							}
						})
					}
				})
			}
		})
	}
	//]]>
</script>

<div class="cbi-value">
	<label class="cbi-value-title">V2ray
		<%:Version%>
	</label>
	<div class="cbi-value-field">
		<div class="cbi-value-description">
			<span>【 <%=v2ray_version%>】</span>
			<input class="cbi-button cbi-input-apply" type="submit" id="_v2ray-check_btn" onclick="onBtnClick_v2ray(this);" value="<%:Manually update%>">
			<span id="_v2ray-check_btn-detail"></span>
		</div>
	</div>
</div>